package org.asiainfo.gateway.filter;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.same.SaSameUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 内部服务外网隔离
 * 转发认证
 *
 * @author dotor-ww
 */
@Component
public class ForwardAuthFilter implements GlobalFilter, Ordered {

    /**
     * 内部服务调用转发拼接Token
     *
     * @param exchange 服务器网络交换
     * @param chain    链
     * @return Mono
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //判断是否开启内部服务调用验证
        if (!SaManager.getConfig().getCheckSameToken()){
            return chain.filter(exchange);
        }

        ServerHttpRequest newRequest = exchange
                .getRequest()
                .mutate()
                .header(SaSameUtil.SAME_TOKEN, SaSameUtil.getToken())
                .build();
        ServerWebExchange newExchange = exchange.mutate().request(newRequest).build();
        return chain.filter(newExchange);
    }

    /**
     * 对象运行顺序
     *
     * @return -200
     */
    @Override
    public int getOrder() {
        return -100;
    }
}
